package com.stkouyu;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.stkouyu.listener.OnLancooSpeechRecognitionListener;
import com.stkouyu.xiansheng.SSoundManager;
import com.stkouyu.xiansheng.entity.ResultDetails;
import com.stkouyu.xiansheng.entity.SoundResult;

import java.io.File;
import java.util.List;
import java.util.UUID;


/**
 * Created by pengmi on 2018/11/21.
 * Description:语音识别
 */

public class LancooSpeechRecognitionManager {

    private static LancooSpeechRecognitionManager lancooSpeechRecognitionManager;
    private Context mContext;
    private OnLancooSpeechRecognitionListener onLancooSpeechRecognitionListener;
    private final int MST_OUTTIME=10;
    private String recordUrl;

    private LancooSpeechRecognitionManager(Context mContext){
        this.mContext=mContext.getApplicationContext();
    }

    public static LancooSpeechRecognitionManager getInstance(Context mContext){
        if(lancooSpeechRecognitionManager==null){
            lancooSpeechRecognitionManager=new LancooSpeechRecognitionManager(mContext);
        }
        return lancooSpeechRecognitionManager;
    }


    /**
     * 语音识别，旧版，只支持英文识别
     */
    public void startSpeechRecognition(String content, OnLancooSpeechRecognitionListener onLancooSpeechRecognitionListener){
        startSpeechRecognition(0,onLancooSpeechRecognitionListener);
    }

    /**
     * 语音识别
     * @param recognitionType 识别类型 0-英文，1-中文
     * @param onLancooSpeechRecognitionListener 识别回调
     */
    public void startSpeechRecognition(int recognitionType,OnLancooSpeechRecognitionListener onLancooSpeechRecognitionListener){
        this.onLancooSpeechRecognitionListener=onLancooSpeechRecognitionListener;
        mHandler.removeMessages(MST_OUTTIME);
        String recordName= UUID.randomUUID()+".wav";
        String recordFilePath=getTempRecordFilePath();
        recordUrl = recordFilePath+"/"+recordName;
        Log.e("eeeee","语音评测url："+ recordUrl);
        SSoundManager.getInstance(mContext).startRecognition(recordUrl,recognitionType,mHandler,onLancooSpeechRecognitionListener);
    }


    /**
     * 结束评测
     * @param isShowSpeechResult 是否执行评测回调
     */
    public void stopSpeechRecognition(boolean isShowSpeechResult){
        Log.e("eeeee","stopSpeechRecognition："+ isShowSpeechResult);
//        SkEgnManager.getInstance(mContext).stopRecord();
        if(!isShowSpeechResult){
            SSoundManager.getInstance(mContext).cancelRecord();
            mHandler.removeMessages(MST_OUTTIME);
        }else{
            SSoundManager.getInstance(mContext).stopRecord();
            mHandler.sendEmptyMessageDelayed(MST_OUTTIME,15000);
        }

    }



    private String getTempRecordFilePath(){
        File targetDir = new File(Environment.getExternalStorageDirectory(),
                "Android/data/" + mContext.getApplicationInfo().packageName + "/files/record/klg");
        if (!targetDir.exists()) {
            boolean isCreate=targetDir.mkdirs();
            if(isCreate){
                Log.e("eeee","路径创建成功");
            }
        }
        return targetDir.getPath();
    }



    private Handler mHandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            mHandler.removeMessages(MST_OUTTIME);
            Log.e("eeee","msg.what:"+msg.what);
            if(msg.what==MST_OUTTIME){
                if(onLancooSpeechRecognitionListener!=null){
                    onLancooSpeechRecognitionListener.onSpeechRecognitionError("out time!");
                }

                if(mContext!=null){
                    LancooSkEgnManager.getInstance(mContext).initSkegn(mContext);
                    Log.e("aaaa","重新进行评测初始化。。。");
                }
            }else if(msg.what==101){
                String error= (String) msg.obj;
                int arg1 = msg.arg1;
                if(arg1==41030||arg1==70017){
                    LancooSkEgnManager.getInstance(mContext).initSkegn(mContext);
                }
                Log.e("123","error:"+error);
                if(onLancooSpeechRecognitionListener!=null){
                    onLancooSpeechRecognitionListener.onSpeechRecognitionError(arg1+"");
                }
            }else if(msg.what==100){
                SoundResult soundResult= (SoundResult) msg.obj;
                List<ResultDetails> wrd_details = soundResult.getWrd_details();
                StringBuilder stringBuilder=new StringBuilder();
                if(wrd_details!=null&&wrd_details.size()>0){
                    for (ResultDetails resultDetails:wrd_details){
                        stringBuilder.append(resultDetails.getText());
                        if(soundResult.getRecognitionType()==0){
                            stringBuilder.append(" ");
                        }
                    }
                }
                Log.e("123","error:"+soundResult.getRecordUrl());
                mHandler.removeMessages(MST_OUTTIME);
                if(onLancooSpeechRecognitionListener!=null){
                    onLancooSpeechRecognitionListener.onSpeechRecognitionEnd(stringBuilder.toString(),soundResult.getRecordUrl());
                }
            }else if(msg.what==104){
                SoundResult soundResult= (SoundResult) msg.obj;
                if(onLancooSpeechRecognitionListener!=null){
                    onLancooSpeechRecognitionListener.onSpeechRecognitionEnd("",soundResult.getRecordUrl());
                }
            }else if(msg.what==105){
                if(onLancooSpeechRecognitionListener!=null){
                    onLancooSpeechRecognitionListener.onSpeechRecognitionStart();
                }
            }else if(msg.what==110){
                if(onLancooSpeechRecognitionListener!=null){
                    onLancooSpeechRecognitionListener.onSpeechRecogniting(0,msg.arg1);
                }
            }
            return false;
        }
    });



}
